package com.czy.daishusys.ui.order;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.czy.daishusys.R;
import com.czy.daishusys.db.UserHelper;
import com.czy.daishusys.entity.GoodsDetailModel;
import com.czy.daishusys.global.Constants;
import com.czy.daishusys.ui.BaseActivity;
import com.czy.daishusys.utils.GsonUtils;
import com.czy.daishusys.utils.JsonUtil;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class GoodsDetailActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.myProgressBar)
    ProgressBar myProgressBar;
    @BindView(R.id.webview)
    WebView webview;
    private ArrayList<String> loadHistoryUrls = new ArrayList<String>();
    private String mLastUrl;
    private String url;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_goods_detail;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        toolbarTitle.setText(R.string.goods_detail);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (webview.canGoBack()) {
                    //过滤是否为重定向后的链接
                    if (loadHistoryUrls.size() > 0) {
                        loadHistoryUrls.remove(loadHistoryUrls.get(loadHistoryUrls.size() - 1));
                        //加载重定向之前的页
                        if (url != null) {
                            webview.loadUrl(Constants.APP_API_BASE + url);
                        }
                    } else {
                        finish();
                    }
                } else {
                    finish();
                }
            }
        });
        getGoodsDetail();
    }

    private void getGoodsDetail() {
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append("session=" + UserHelper.getInstance().getSessionInfoModel(this).getSession() + "&");
        if (getIntent().getIntExtra("goodsId", 0) != 0) {
            urlBuilder.append("goodsId=" + getIntent().getIntExtra("goodsId", 0) + "&");
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra("specGroupKey"))) {
            urlBuilder.append("specGroupKey=" + getIntent().getStringExtra("specGroupKey") + "&");
        }
        url = "/pub/goodsView?" + urlBuilder;
        initWebView(url);
    }


    @Override
    protected void updateViews() {

    }

    private void initWebView(String url) {
        mMProgressDialog.show();
        WebSettings settings = webview.getSettings();
        settings.setAppCacheEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setJavaScriptEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setSupportZoom(true);
        webview.loadUrl(Constants.APP_API_BASE + url);
        webview.setWebViewClient(new MyWebViewClient());
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    mMProgressDialog.dismiss();
                    myProgressBar.setVisibility(View.GONE);
                } else {
                    if (View.GONE == myProgressBar.getVisibility()) {
                        myProgressBar.setVisibility(View.VISIBLE);
                    }
                    myProgressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }


        });
        webview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                WebView.HitTestResult hr = ((WebView) view).getHitTestResult();
                if (hr != null && loadHistoryUrls != null) {
                    if (loadHistoryUrls.size() < 1) {
                        if (loadHistoryUrls.isEmpty() || !loadHistoryUrls.get(loadHistoryUrls.size() - 1).equals(mLastUrl)) {
                            loadHistoryUrls.add(mLastUrl);
                        }
                    }


                }
                return false;
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webview.destroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        //判断是否可以返回操作
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
            //过滤是否为重定向后的链接
            if (loadHistoryUrls.size() > 0) {
                loadHistoryUrls.remove(loadHistoryUrls.get(loadHistoryUrls.size() - 1));
                //加载重定向之前的页
                if (url != null) {
                    webview.loadUrl(Constants.APP_API_BASE + url);
                }

            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;


        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mLastUrl = url;

        }
    }
}
